<template>
    <view class="container">
        <!-- 加载状态 -->
        <view v-if="loading" class="loading-container">
            <view class="loading-spinner"></view>
            <text class="loading-text">加载中...</text>
        </view>
        
        <!-- 错误提示 -->
        <view v-if="error" class="error-container">
            <text class="error-text">{{errorMessage}}</text>
            <button class="retry-btn" @click="fetchCoupons">重试</button>
        </view>
        
        <!-- 空状态提示 -->
        <view v-if="!loading && !error && coupons.length === 0" class="empty-container">
            <text class="empty-text">暂无可用优惠券</text>
        </view>
        
        <!-- 卡券列表 -->
        <view v-if="!loading && !error && coupons.length > 0" class="coupon-list">
            <!-- 循环渲染卡券 -->
            <view v-for="(coupon, index) in coupons" :key="coupon.id" class="coupon-item">
                <view class="coupon-info">
                    <view class="coupon-title">{{coupon.title}}</view>
                    <view class="coupon-price">{{coupon.price}} 元</view>
                </view>
                <view class="coupon-details">
                    <view class="coupon-limits">
                        <view class="limit-item">可用次数: {{coupon.remainTimes || 1}}次</view>
                        <view class="limit-item">可抵时长: {{coupon.duration}} 小时</view>
                        <view class="limit-item">房间类型: {{coupon.roomType}}</view>
                    </view>
                    <button 
                        v-if="coupon.stock !== 0" 
                        class="buy-btn" 
                        @click="purchaseCoupon(coupon.id)"
                    >购买</button>
                    <button v-else class="sold-out-btn">已抢光了</button>
                </view>
                <view class="coupon-terms">
                    <text class="term-item">适用时段: {{coupon.periodLimit || '全天'}}</text>
                    <text class="term-item">有效期至: {{formatDate(coupon.expireDate)}}</text>
                    <text v-if="coupon.terms" class="term-item">{{coupon.terms}}</text>
                </view>
            </view>
        </view>

        <!-- 底部导航栏 -->
        <tab-bar active="coupon"></tab-bar>
    </view>
</template>

<script lang="ts" setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import TabBar from '@/components/tabBar/TabBar.vue';
import api from '@/utils/api.js';

// 设置导航栏标题
uni.setNavigationBarTitle({
    title: '领券中心'
});

// 数据
const coupons = ref([]);
const loading = ref(true);
const error = ref(false);
const errorMessage = ref('');

// 获取优惠券列表
const fetchCoupons = async () => {
    loading.value = true;
    error.value = false;
    
    try {
        const response = await api.coupon.getAll();
        if (response.success) {
            coupons.value = response.data;
        } else {
            throw new Error(response.message || '获取优惠券失败');
        }
    } catch (err) {
        console.error('获取优惠券列表失败:', err);
        error.value = true;
        errorMessage.value = err.message || '获取优惠券失败，请稍后重试';
    } finally {
        loading.value = false;
    }
};

// 购买优惠券
const purchaseCoupon = async (couponId) => {
    try {
        uni.showLoading({
            title: '正在准备支付...',
            mask: true
        });
        
        const response = await api.coupon.purchase(couponId);
        
        uni.hideLoading();
        
        if (response.success) {
            console.log('创建支付订单成功:', response.data);
            
            // 如果返回了支付URL，则跳转到支付页面
            if (response.data && response.data.payment_url) {
                // 保存支付信息到本地，以便在支付完成后使用
                uni.setStorageSync('CURRENT_BUSINESS_TYPE', 'coupon');
                uni.setStorageSync('CURRENT_BUSINESS_ID', response.data.orderId);
                uni.setStorageSync('COUPON_ID', response.data.couponId);
                
                // 跳转到支付页面
                uni.navigateTo({
                    url: response.data.payment_url
                });
            } else {
                // 如果没有支付URL但支付成功（可能是免费优惠券）
                uni.showToast({
                    title: response.message || '购买成功',
                    icon: 'success'
                });
                
                // 刷新优惠券列表
                fetchCoupons();
            }
        } else {
            throw new Error(response.message || '购买失败');
        }
    } catch (err) {
        uni.hideLoading();
        
        // 检查是否是未登录错误
        if (err.message.includes('未登录') || err.message.includes('登录已过期')) {
            uni.showModal({
                title: '提示',
                content: '请先登录',
                confirmText: '去登录',
                success: (res) => {
                    if (res.confirm) {
                        uni.navigateTo({
                            url: '/pages/login/login'
                        });
                    }
                }
            });
        } else {
            uni.showToast({
                title: err.message || '购买失败，请稍后重试',
                icon: 'none'
            });
        }
    }
};

// 格式化日期
const formatDate = (dateString) => {
    if (!dateString) return '';
    const date = new Date(dateString);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

// 处理全局tab切换事件
const handleGlobalTabChange = (tab) => {
    if (tab === 'coupon') return; // 当前已经是卡券页，不需要处理

    const routes = {
        'home': '/pages/index/index',
        'order': '/pages/order/order',
        'user': '/pages/user/user'
    };

    const url = routes[tab];
    if (!url) return;

    // 尝试使用redirectTo，这对非tabBar页面有效
    uni.redirectTo({
        url,
        fail: () => {
            // 如果失败则尝试强制刷新到新页面
            if (typeof window !== 'undefined') {
                window.location.replace('#' + url);
            }
        }
    });
};

// 生命周期钩子
onMounted(() => {
    // 获取优惠券列表
    fetchCoupons();
    
    // 监听全局tab切换事件
    uni.$on('tabChange', handleGlobalTabChange);
});

// 组件销毁前移除事件监听
onBeforeUnmount(() => {
    uni.$off('tabChange', handleGlobalTabChange);
});
</script>

<style>
page {
    background-color: #f5f5f5;
    min-height: 100%;
}

.container {
    padding-bottom: 150rpx;
    padding-top: 20rpx;
}

.loading-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 300rpx;
}

.loading-spinner {
    width: 60rpx;
    height: 60rpx;
    border: 6rpx solid #f3f3f3;
    border-top: 6rpx solid #7FB992;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-bottom: 20rpx;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

.loading-text {
    font-size: 28rpx;
    color: #999;
}

.error-container, .empty-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 100rpx 0;
}

.error-text, .empty-text {
    font-size: 28rpx;
    color: #999;
    margin-bottom: 30rpx;
}

.retry-btn {
    background-color: #7FB992;
    color: #FFFFFF;
    font-size: 28rpx;
    border-radius: 100rpx;
    padding: 10rpx 40rpx;
}

.coupon-list {
    padding: 20rpx;
}

.coupon-item {
    background-color: #FFFFFF;
    border-radius: 16rpx;
    margin-bottom: 20rpx;
    padding: 30rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.coupon-info {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 20rpx;
}

.coupon-title {
    font-size: 32rpx;
    font-weight: 500;
    color: #333;
    flex: 1;
}

.coupon-price {
    font-size: 32rpx;
    font-weight: 500;
    color: #7FB992;
    white-space: nowrap;
    margin-left: 20rpx;
}

.coupon-details {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
}

.coupon-limits {
    display: flex;
    gap: 20rpx;
}

.limit-item {
    background-color: rgba(127, 185, 146, 0.1);
    color: #7FB992;
    font-size: 24rpx;
    padding: 8rpx 20rpx;
    border-radius: 8rpx;
}

.buy-btn {
    background-color: #7FB992;
    color: #FFFFFF;
    font-size: 28rpx;
    border-radius: 100rpx;
    padding: 10rpx 40rpx;
    margin: 0;
    min-width: 140rpx;
    text-align: center;
}

.sold-out-btn {
    background-color: #a0a0a0;
    color: #FFFFFF;
    font-size: 28rpx;
    border-radius: 100rpx;
    padding: 10rpx 40rpx;
    margin: 0;
    min-width: 140rpx;
    text-align: center;
}

.coupon-terms {
    display: flex;
    flex-direction: column;
    gap: 10rpx;
}

.term-item {
    font-size: 24rpx;
    color: #999;
}
</style>
